package com.linln.component.shiro;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.linln.modules.system.repository.UserRepository;
import io.jsonwebtoken.Claims;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

import com.linln.component.shiro.config.JwtUtils;

/**
 * 处理session超时问题拦截器
 * @author 小懒虫
 * @date 2018/8/14
 */
public class UserAuthFilter extends AccessControlFilter {

    //读取yml配置
    @Value("${hostInfo.middle}")
    private String middle;
    @Value("${hostInfo.host}")
    private String host;


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            Subject subject = getSubject(request, response);
            return subject.getPrincipal() != null && (subject.isRemembered() || subject.isAuthenticated());
        }
    }

    //原拦截方法
//    @Override
//    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//        HttpServletRequest httpRequest = WebUtils.toHttp(request);
//        HttpServletResponse httpResponse = WebUtils.toHttp(response);
//
//        if (httpRequest.getHeader("X-Requested-With") != null
//                && "XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) {
//            httpResponse.sendError(HttpStatus.UNAUTHORIZED.value());
//        } else {
//            redirectToLogin(request, response);
//        }
//        return false;
//    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)) {
            sendRedirect(httpResponse);
            return false;
        }

        try {

            Claims claims = JwtUtils.parseToken(token);

            // 验证有效期
            if (claims.getExpiration().before(new Date())) {
                sendRedirect(httpResponse);
               // throw new ExpiredJwtException(null, claims, "Token已过期");
                return false;
            }

            // 获取用户信息
            Long userId = Long.valueOf(claims.getSubject());
            String target = request.getParameter("target");
            httpRequest.getSession().setAttribute("tempUserId", userId);
            httpRequest.getSession().setAttribute("target", target);
            httpResponse.sendRedirect("/login");


//            request.setAttribute("userId", userId);
//            redirectToLogin(request, response);


            // 存储用户信息（根据子系统需要实现）
//            request.getSession().setAttribute("currentUser",
//                    new SessionUser(userId, platformId));

            return true;

        } catch (Exception e) {
            sendRedirect(httpResponse);
            return false;
        }




//        if (httpRequest.getHeader("X-Requested-With") != null
//                && "XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) {
//            httpResponse.sendError(HttpStatus.UNAUTHORIZED.value());
//        } else {
//            redirectToLogin(request, response);
//        }
//        return false;
    }

    private void sendRedirect(HttpServletResponse response) throws IOException {
        response.sendRedirect("/login");
        //response.sendRedirect(middle+"/login?redirect="+host);
    }
}
